import { AbpHttpConfigurationService, AbpHttpInterceptor } from 'abp-ng2-module';
import { Injectable, Injector } from '@angular/core';
import { HttpRequest, HttpHeaders } from '@angular/common/http';


@Injectable()
export class AppHttpInterceptor extends AbpHttpInterceptor {
    //请求头是大小写不敏感的，为避免不必要的误会，还是改小写吧
    protected MenuIdHeaderName =  'menuid';

    constructor(configuration: AbpHttpConfigurationService, _injector: Injector) {
        super(configuration, _injector);
    }

    override normalizeRequestHeaders(request: HttpRequest<any>): HttpRequest<any> {
        var modifiedHeaders = new HttpHeaders();
        modifiedHeaders = request.headers.set("Pragma", "no-cache")
            .set("Cache-Control", "no-cache")
            .set("Expires", "Sat, 01 Jan 2000 00:00:00 GMT");
        modifiedHeaders = this.addXRequestedWithHeader(modifiedHeaders);
        modifiedHeaders = this.addAuthorizationHeaders(modifiedHeaders);
        modifiedHeaders = this.addAspNetCoreCultureHeader(modifiedHeaders);
        modifiedHeaders = this.addAcceptLanguageHeader(modifiedHeaders);
        modifiedHeaders = this.addTenantIdHeader(modifiedHeaders);
        modifiedHeaders = this.addMenuIdHeader(modifiedHeaders, request);

        return request.clone({
            headers: modifiedHeaders
        });
    }

    protected addMenuIdHeader(headers: HttpHeaders, request: HttpRequest<any>) {

        if (request.body && typeof request.body === 'string') {
            let jsonData = JSON.parse(request.body);
            let menuId = jsonData['menuId'];
            if (!menuId) {
                menuId = jsonData['menuFid'];
            }
            if (menuId && headers && !headers.has(this.MenuIdHeaderName)) {
                headers = headers.set(this.MenuIdHeaderName, menuId.toString());
                return headers;
            }
        } else {
            let menuId = this.getQueryVariable(request.urlWithParams, ['menuId', 'MenuId', 'menuFid', 'MenuFid']);
            if (menuId && headers && !headers.has(this.MenuIdHeaderName)) {
                headers = headers.set(this.MenuIdHeaderName, menuId);
                return headers;
            }
        }

        return headers;
    }

    private getQueryVariable(url: string, variables: string[]): string {
        if (url.indexOf('?') > 0) {
            let query = url.split('?')[1];
            let vars = query.split("&");
            for (let i = 0; i < vars.length; i++) {
                let pair = vars[i].split("=");
                let key = pair[0];
                for (let j = 0; j < variables.length; j++) {
                    if (key == variables[j]) {
                        return pair[1];
                    }
                }
            }
        }
        
        return null;
    }
}
